from pyftpdlib import ftpserver

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'ceemtu.settings'

from ceemtu.cetcore.models import Archive

from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.conf import settings

read_perms = "elr"
write_perms = "adfmw"

ftp_none = 0
ftp_upload = 1
ftp_download = 2

class CeemtuFtpAuthorizer:

    def __init__(self):
        print "Authorizer created"
        pass

    def has_user(self, username):
        try:
            u = User.objects.get(username = username)            
            return True
        except:
            return False

    def get_home_dir(self, username):
        try:
            #TODO: if superuser return ftp-folder-root
            #return settings.FTP_FOLDER# os.path.join(settings.USERS_FOLDER, username)
            return os.path.join(settings.USERS_FOLDER, username)
        except:
            return None

    def get_msg_login(self, username):
        user_home = os.path.join(settings.USERS_FOLDER, username)
        for folder in ('incoming', 'music', 'photos','movies', 'files'):
            p = os.path.join(user_home, folder)
            if not os.path.exists(p):
                os.makedirs(p)
        return 'Welcome to the CeemTu-FTP Server'

    def get_msg_quit(self, username):
        return 'Please come again'

    def r_perm(self, username, obj=None):
        try:
            return read_perms
        except:
            return False

    def w_perm(self, username, obj=None):
        try:
            return write_perms
        except:
            return False

    def has_perm(self, username, perm, path=None):
        #TODO: if the user is superuser grant full access no-matter-what!!
        current_path = os.path.split(path[len(settings.FTP_FOLDER):].lower())[0]
        if current_path == '/users/%s' % username and perm in write_perms+read_perms:
            return True
        else:
            return perm in read_perms
    
    def impersonate_user(self, username, password):
        """Impersonate another user (noop).

        It is always called before accessing the filesystem.
        By default it does nothing.  The subclass overriding this
        method is expected to provide a mechanism to change the
        current user.
        """

    def terminate_impersonation(self):
        """Terminate impersonation (noop).

        It is always called after having accessed the filesystem.
        By default it does nothing.  The subclass overriding this
        method is expected to provide a mechanism to switch back
        to the original user.
        """

    def get_user(self, username):
        try:
            return User.objects.get(username=username)
        except:
            raise

    def validate_authentication(self, username, password):
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                return True
        return False

#class CeemtuFtpHandler(ftpserver.DTPHandler):
#    
#    def handle_close(self):
#        action = ftp_none
#        if not self.receive:
#            action = ftp_download
#        else:
#            action = ftp_upload

#        ftpserver.DTPHandler.handle_close(self)
        #if self.file_obj and action == ftp_upload:
        #    usr = User.objects.filter(username = self.cmd_channel.username)[0]
        #    archives = Archive.objects.filter(user = usr, name = 'uploads')
        #    if not archives:
        #        Archive.objects.create(
        #            user = models.ForeignKey(User)
        #            name = models.CharField(max_length=100)
        #            #path = models.FilePathField(path=".", max_length = 500)
        #            path = models.CharField(max_length=500)
        #            extensions = models.ManyToManyField(FileExtension)
        #            filesystem = models.ForeignKey(FileSystemType, null = True, blank = True)
        #            media_label = models.CharField(max_length=100, null = True, blank = True)
        #            description = models.TextField(null = True, blank = True)
        #            tags = TagField()
        #            needs_review = models.BooleanField()
        #            generate_checksums = models.BooleanField()
        #        
        #            last_update = models.DateTimeField(null = True)
        #            scan_interval = models.IntegerField(null = True, blank = True)
        #            scan_interval_type = models.IntegerField(null = True, blank = True, choices = TIME_DURATION)
        #            dirty = models.BooleanField()
        #            writable = models.BooleanField()
        #            available = models.BooleanField()
        #            
        #        )
            
            #pa = PrimitiveArchive('uploads_%s' % self.cmd_channel.username, os.path.join(settings.USERS_FOLDER))
            #if not pa.get_archive_settings():
            #        pa.username = user.username
            #        pa.email = user.email
            #        pa.generate_checksums = True
            #        pa.extensions = [fe.extension for fe in FileExtensions.objects.all()]
            #        pa.set_archive_settings()
            #pa.process_file(self.file_obj.name)
            
if __name__ == "__main__":
    authorizer = CeemtuFtpAuthorizer()
    ftp_handler = ftpserver.FTPHandler
    ftp_handler.authorizer = authorizer
    #ftp_handler.dtp_handler = CeemtuFtpHandler
    ftpd = ftpserver.FTPServer((settings.FTP_ADDRESS, settings.FTP_PORT), ftp_handler)
    ftpd.serve_forever()